package com.rc.saas.mini.config;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

/**
 * @Description: Nacos服务启动自动注册配置
 */
@Configuration
public class NacosRegisterConfig implements ApplicationRunner {
    @Value("${server.port}")
    Integer port;

    @Value("${spring.application.name}")
    private String applicationName;

    @NacosInjected
    private NamingService namingService;

    @Autowired(required = false)
    private NacosAutoServiceRegistration registration;

//    @PostConstruct
//    public void registerInstance() throws NacosException {
//        namingService.registerInstance(applicationName, "119.23.35.158",serverPort,"DEFAULT");
//    }

    /**
     * 防止war包 nacos端口无法注册
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (registration != null && port != null) {
//            Integer tomcatPort = port;
            try {
//                tomcatPort = new Integer(port);
                registration.setPort(port);
                registration.start();
            } catch (Exception e) {
                System.out.println("使用内置tomcat启动，不需要单独注册nacos服务");
            }
        }
    }
}